<template>
  <div>
    <window
      ref="win"
      title="退费申请"
    >
      <form
        class="am-form tpl-form-border-form tpl-form-border-br"
        data-am-validator
        :id="id"
        onsubmit="return false "
      >
        <div class="am-u-sm-12 am-scrollable-horizontal">
          <div
            class="conentTable"
            v-for="(item, index) in studentRegDetailArray"
            :key="index"
          >
            <div class="am-u-sm-12 am-text-left am-margin-top-sm bold-font">班级信息</div>
            <table
              width="100%"
              class="am-table am-table-bordered am-table-compact "
            >
              <colgroup>
                <col width="100" />
                <col width="100" />
                <col width="100" />
                <col width="100" />
                <col width="100" />
                <col width="100" />
              </colgroup>
              <tbody>
                <tr>
                  <td class="bgColor">期数：</td>
                  <td>{{item.courseClass.periodName}}</td>
                  <td class="bgColor">业务组：</td>
                  <td>{{item.courseClass.busTeamName}}</td>
                  <td class="bgColor">班级名称：</td>
                  <td>{{item.courseClass.className}}</td>
                </tr>
                <tr>
                  <td class="bgColor">班级编号：</td>
                  <td>{{item.courseClass.classNo}}</td>
                  <td class="bgColor">任课老师：</td>
                  <td>{{item.courseClass.teacherName}}</td>
                  <td class="bgColor">教室：</td>
                  <td>{{item.courseClass.roomName}}</td>
                </tr>
                <tr>
                  <td class="bgColor">开课日期：</td>
                  <td>{{item.courseClass.startCourseTime | formatDate}}</td>
                  <td class="bgColor">报读总讲次：</td>
                  <td>{{item.studentReg.regLectureAmount}}</td>
                  <td colspan="2"></td>

                </tr>
                <tr>
                  <td class="bgColor">原价：</td>
                  <td>{{item.studentReg.srcTotalAmount}}</td>
                  <td class="bgColor">金额：</td>
                  <td>{{item.studentReg.totalAmount}}</td>
                  <td class="bgColor">已交金额：</td>
                  <td>{{item.studentReg.payAmount}}</td>
                </tr>
                <tr v-if="availableRefundLectures[item.studentReg.regId] && formData.refundLectureDetailVos[index]">
                  <td class="bgColor">从哪一讲退</td>
                  <td colspan="7">
                    <span
                      v-for="(lItem,lIndex) in availableRefundLectures[item.studentReg.regId]"
                      :key="lIndex"
                    >
                      <label class="am-checkbox-inline">
                        <input
                          @change="lectureChange(lItem, index, item)"
                          type="radio"
                          :value="lItem.lectureNo"
                          :name="'refundLectureFromNo_'+ index"
                          v-model="formData.refundLectureDetailVos[index].refundLectureFrom"
                        > 第{{lItem.lectureNo}}讲<span class="am-text-danger">({{ { '0':'出勤', '1':'缺勤', '2':'迟到', '3':'请假' }[lItem.attendanceStatus] || '未考勤' }})</span>
                      </label>
                      <br v-if="( lIndex + 1 ) % 6 == 0">
                    </span>

                  </td>
                </tr>

                <tr v-if="formData.refundLectureDetailVos[index]">
                  <td class="bgColor">应退金额</td>
                  <td colspan="7">
                    <span class="am-text-danger">￥{{remaining[index] | formatNumber(2)}}</span>
                  </td>
                </tr>
                <tr v-if="formData.refundLectureDetailVos[index]">
                  <td class="bgColor">确认退款金额</td>
                  <td>
                    <input
                      type="number"
                      class="am-input-sm"
                      v-model="formData.refundLectureDetailVos[index].finalRefundAmount"
                      min="0"
                      @input="checkFinalRefundAmount(index)"
                    >
                  </td>
                  <td colspan="6">
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <table
            width="100%"
            class="am-table am-table-bordered am-table-compact am-text-nowrap"
          >
            <tbody>
              <tr>
                <td class="bgColor">退费方式</td>
                <td colspan="7">
                  <label class="am-checkbox-inline">
                    <input
                      type="radio"
                      value="3"
                      name="refundWay"
                      v-model="formData.refundWay"
                    > 账户余额
                  </label>
                  <label class="am-checkbox-inline">
                    <input
                      type="radio"
                      value="4"
                      name="refundWay"
                      v-model="formData.refundWay"
                    > 银行卡转账
                  </label>
                </td>
              </tr>

              <tr>
                <td class="bgColor">退费原因</td>
                <td colspan="7">

                  <el-checkbox-group v-model="reasonSelect">
                    <el-checkbox label="进度和学校进度不一致"></el-checkbox>
                    <el-checkbox label="学校这个时间补课或有活动"></el-checkbox>
                    <el-checkbox label="校区砍班"></el-checkbox>
                    <el-checkbox label="不适应任课老师"></el-checkbox>
                    <el-checkbox label="与家庭其他事安排冲突"></el-checkbox><br>
                    <el-checkbox label="报了竞品同类机构"></el-checkbox>
                    <el-checkbox label="没有达到预期的学习效果"></el-checkbox>
                    <el-checkbox label="其他原因"></el-checkbox>
                  </el-checkbox-group>

                </td>
              </tr>
              <tr>
                <td class="bgColor">退费详情</td>
                <td colspan="7">
                  <input
                    type="text"
                    placeholder="退费详情"
                    class="am-input-sm "
                    v-model="formData.refundDetail"
                  >
                </td>
              </tr>

              <template v-if="formData.refundWay == 4 ">
                <tr>
                  <td class="bgColor">转账银行</td>
                  <td colspan="2"><input
                      type="text"
                      class="am-input-sm"
                      v-model="formData.bankName"
                    ></td>
                  <td class="bgColor">开户城市</td>
                  <td colspan="2"><input
                      type="text"
                      class="am-input-sm"
                      v-model="formData.bankCity"
                    ></td>
                </tr>

                <tr>
                  <td class="bgColor">姓名</td>
                  <td colspan="2"><input
                      type="text"
                      class="am-input-sm"
                      v-model="formData.cardUser"
                    ></td>
                  <td class="bgColor">转账账号</td>
                  <td colspan="2"><input
                      type="text"
                      class="am-input-sm"
                      v-model="formData.cardNo"
                    ></td>
                </tr>
              </template>
              <tr>
                <td class="bgColor">退费总金额</td>
                <td colspan="4">
                  <span class="am-text-danger">￥{{allPrice || 0}}</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="am-u-sm-12 am-text-center am-margin-top-lg">
          <button
            type="button"
            class="am-btn am-btn-primary"
            @click="confirmToRefund"
          >确定</button>
          <a
            href="javascript:void(0)"
            data-am-modal-close
          >
            <button class="am-btn am-btn-primary">取消</button>
          </a>
        </div>
      </form>
    </window>
    <div>
      <student-refund-preview ref="previewStudentRefund"></student-refund-preview>
    </div>

  </div>

</template>
<style scoped>
.bold-font {
  font-weight: bold;
}

.bgColor {
  background-color: #eee;
  text-align: center;
}
.refundWidth {
  width: 50%;
}
</style>

<script>
import io from '../../lib/io'
import math from '../../lib/math'
import StudentRefundPreview from './StudentRefundPreview.vue'

export default {
  data: function() {
    return {
      formData: {
        refundWay: 4,
        bankName: '',
        bankCity: '',
        cardUser: '',
        cardNo: '',
        description: '',
        refundLectureDetailVos: []
      },
      studentRegDetailArray: [],
      remaining: [],
      availableRefundLectures: {},
      regId: '',
      reasonSelect: [],
      refundDetail: '',
      otherReason: false,
      regArray: [],
      allPrice: ''
    }
  },
  components: { StudentRefundPreview },
  methods: {
    lectureChange(item, index, studentRegDetail) {
      this.calRemaining(item, index, studentRegDetail)
    },
    countAllPrice() {
      let price = 0
      for (let item of this.formData.refundLectureDetailVos) {
        price = price + Number(item.finalRefundAmount || 0)
      }
      this.allPrice = price.toFixed(2)
    },
    reset: function() {
      this.formData.refundWay = 4
      this.formData.bankName = ''
      this.formData.bankCity = ''
      this.formData.cardUser = ''
      this.formData.cardNo = ''
      this.formData.refundLectureDetailVos = []
      this.formData.reasonSelect = []
      this.formData.refundDetail = ''
      this.formData.description = ''
      this.remaining = []
      this.allPrice = ''
    },
    loadClassMessageData: function() {
      var _this = this
      io.post(
        io.apiAdminStudentRegDetails,
        { regIds: _this.regArray.join(',') },
        ret => {
          if (ret.success) {
            let tempArray = ret.data
            for (let item of tempArray) {
              item.studentReg.startAmount = parseInt(
                item.studentReg.startAmount
              )
              item.studentReg.endAmount = parseInt(item.studentReg.endAmount)
              item.studentReg.refundAmount = parseFloat(
                item.studentReg.refundAmount || 0
              )
              item.studentReg.regLectureAmount =
                item.studentReg.endAmount - item.studentReg.startAmount + 1
              item.courseClass.lectureAmount = parseInt(
                item.courseClass.lectureAmount
              )
              this.formData.refundLectureDetailVos.push({
                regId: item.studentReg.regId
              })
            }

            _this.studentRegDetailArray = tempArray
          } else {
            _this.$alert(ret.desc)
          }
        }
      )
    },
    loadAttend: function() {
      var _this = this
      io.post(
        io.apiAdminQueryAttendOfStudents,
        { regIds: _this.regArray.join(',') },
        function(ret) {
          if (ret.success) {
            _this.availableRefundLectures = ret.data
          } else {
            _this.$alert(ret.desc)
          }
        }
      )
    },
    calRemaining: function(obj, index, studentRegDetail) {
      let refundLectureFrom = obj.lectureNo
      let remainPrice = !refundLectureFrom
        ? 0
        : math.mul(
            studentRegDetail.studentReg.endAmount - refundLectureFrom + 1,
            math.div(
              studentRegDetail.studentReg.totalAmount -
                studentRegDetail.studentReg.refundAmount,
              studentRegDetail.studentReg.regLectureAmount
            )
          ) || '0'
      // this.remaining.splice(index, 1, remainPrice)
      this.$set(this.remaining, index, remainPrice)
      this.formData.refundLectureDetailVos[
        index
      ].finalRefundAmount = remainPrice.toFixed(2)
      this.$set(
        this.formData.refundLectureDetailVos,
        index,
        this.formData.refundLectureDetailVos[index]
      )
      this.countAllPrice()
    },
    checkFinalRefundAmount(index) {
      let finalRefundAmount = this.formData.refundLectureDetailVos[index]
        .finalRefundAmount
      let remaining = this.remaining[index]
      if (finalRefundAmount <= 0 || finalRefundAmount > remaining) {
        this.formData.refundLectureDetailVos[
          index
        ].finalRefundAmount = this.remaining[index].toFixed(2)
        this.$set(
          this.formData.refundLectureDetailVos,
          index,
          this.formData.refundLectureDetailVos[index]
        )
      }
      this.countAllPrice()
    },
    confirmToRefund: function() {
      var _this = this
      if (this.formData.refundWay == 4) {
        if (!this.formData.bankName) {
          this.$alert('请填开户银行')
          return
        }
        if (!this.formData.bankCity) {
          this.$alert('请填开户城市')
          return
        }

        if (!this.formData.cardUser) {
          this.$alert('请填姓名')
          return
        }

        if (!this.formData.cardNo) {
          this.$alert('请填转账账号')
          return
        }

        // if (!/^\d{16}|\d{19}$/.test(this.formData.cardNo)) {
        //   this.$alert('请确认转账账号是16或19位')
        //   return
        // }
      }
      if (_this.formData.refundLectureDetailVos.length > 0) {
        for (let item of _this.formData.refundLectureDetailVos) {
          if (!item.refundLectureFrom) {
            this.$alert('请选择退费讲次')
            return
          }
        }
      }
      if (!this.reasonSelect.length) {
        this.$alert('请勾选退费原因')
        return
      }
      if (!this.formData.refundDetail) {
        this.$alert('请填写退费详情')
        return
      }
      this.formData.description =
        this.reasonSelect.join(',') + ':' + this.formData.refundDetail
      _this.$showLoading()

      io.postPlayload(io.saveStudentRefundClassList, _this.formData, function(
        ret
      ) {
        _this.$hiddenLoading()
        if (ret.success) {
          _this.$refs.win.close()
          _this.$emit('completed')
          if (_this.formData.refundWay == 3) {
            _this.$root.$emit('mainAccount:change')
            _this.$toast('已经退费成功')
          } else {
            _this.$toast('已接受退款申请')
          }
          let studentRefundId = (ret.data || []).map(item => {
            return item.studentRefundId
          })
          _this.previewRefund(studentRefundId.join(','))
        } else {
          _this.$alert(ret.desc || '申请失败')
        }
      })
    },
    previewRefund: function(studentRefundId) {
      this.$refs.previewStudentRefund.studentRefundId = studentRefundId
      this.$refs.previewStudentRefund.show()
    },
    show: function() {
      this.$refs.win.show({
        width: 1000
      })
      this.reset()
      this.loadClassMessageData()
      this.loadAttend()
    }
  }
}
</script>
